package com.qys.livesMall.framework.utils;

/**
 * @packageName:
 * @className:SnowflakeGenerator
 * @Description:
 * @author:guomx
 * @date:2023/6/516:26
 */
public class SnowflakeGenerator {
    private static final long START_TIMESTAMP = 1630416000000L; // 设置起始时间戳，单位：毫秒
    private static final long MAX_MACHINE_ID = 31L; // 机器ID的最大值，范围：0-31
    private static final long MAX_SEQUENCE = 16383L; // 序列号的最大值，范围：0-16383

    private static long machineId;
    private static long sequence = 0L;
    private static long lastTimestamp = -1L;

    private SnowflakeGenerator() {
        // 私有构造函数，防止实例化
    }

    public static synchronized long generateSnowflakeID(long machineId) {
        if (machineId < 0 || machineId > MAX_MACHINE_ID) {
            throw new IllegalArgumentException("Machine ID must be between 0 and " + MAX_MACHINE_ID);
        }

        long currentTimestamp = System.currentTimeMillis();
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("Invalid system clock.");
        }

        if (currentTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                currentTimestamp = nextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = currentTimestamp;

        return ((currentTimestamp - START_TIMESTAMP) << 10)
                | (machineId << 4)
                | sequence;
    }

    private static long nextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    public static void main(String[] args) {
        long machineId = 1L; // 设置机器ID
        for (int i = 0; i < 10; i++) {
            long id = generateSnowflakeID(machineId);
            System.out.println(id);
        }
    }
}


